Server ActionsでInfinite Scroll
server actionsで無限スクロール
https://infinite-scroll-with-actions.vercel.app/
https://github.com/mrsekut/infinite-scroll-with-actions/tree/2b036a7236b4d6408fa64901431cf78718d6592c
別に何も難しくない
Server Actionsだからどうのという要素がない
https://gyazo.com/74881c1b7988a77ed6f67bf12339316b
code:ts
type LoadMore<T> = {
getNext: () => Promise<T[]>;
handleLoad: (items: T[]) => void;
};
const useLoadMore = <T,>({ getNext, handleLoad }: LoadMore<T>) => {
const isLoading, setIsLoading = useState(false);
const hasMore, setHasMore = useState(true);
const ref = useRef<HTMLDivElement | null>(null);
const loadMore = useCallback(async () => {
if (isLoading || !hasMore) return;
setIsLoading(true);
try {
const newItems = await getNext();
if (newItems.length === 0) {
setHasMore(false);
} else {
handleLoad(newItems);
}
} catch (error) {
console.error(error);
} finally {
setIsLoading(false);
}
}, isLoading, hasMore, getNext, handleLoad);
useEffect(() => {
const observer = new IntersectionObserver(entries => {
if (entries0.isIntersecting) {
loadMore();
}
});
if (ref.current) {
observer.observe(ref.current);
}
return () => observer.disconnect();
}, loadMore);
const Sentinel = () => <div ref={ref} style={{ height: '20px' }} />;
return { Sentinel, isLoading };
};
Intersection Observerを使うのは賢い
要素の高さを計算してどうのこうのということをしないで済む